import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Col,
  Form,
  Input,
  Row,
  Select,
  Tree,
  message,
  Upload,
  Icon,
  Modal,
  Button,
  Spin,
} from 'antd';
import BTreeSelect from '../../../components/nd_component/BTreeSelect';
import BraftEditor from 'braft-editor';
const { TreeNode } = Tree;
import SelectProductInfo from './SelectProductInfo';

const { Item: FormItem } = Form;
const Option = Select.Option;
@Form.create()
@connect(({ productHomeImg }) => ({ productHomeImg }))
export default class ProductHomeImgAddOrUpdate extends Component {
  state = {
    checkedKeys: [],
    previewVisible: false,
    previewImage: '',
    selectProductListVisible: false,
    record: {
      picList: [],
    },
    selectProductList: [],
  };

  //设置产品信息
  setProductInfo = data => {
    this.setState({ selectProductList: data });
  };

  componentDidMount() {
    const { record, dispatch } = this.props;
    if (record.id) {
      let data = record;
      let obj = {};
      obj.thumbUrl = record.imgUrl;
      obj.uid = '1';
      let picList = [];
      picList.push(obj);
      data.picList = picList;
      this.setState({ record: data });
    }
  }
  okHandler = () => {
    this.props.form.validateFields((err, fields) => {
      if (!err) {
        const dataToSubmit = {
          ...fields,
        };
        this.props.onSubmit(err, dataToSubmit);
      }
    });
  };

  //校验图片数据
  checkImageList = (rule, value, callback) => {
    const { form } = this.props;
    const { picList } = this.state.record;
    if (picList.length === 0 && value.length === 0) {
      callback('error');
    } else {
      callback();
    }
  };
  //关闭大图展示框
  handleCancel = () => this.setState({ previewVisible: false });
  //查看大图
  handlePreview = async file => {
    this.setState({
      previewImage: file.thumbUrl,
      previewVisible: true,
    });
  };
  //上传文件
  handleChange = info => {
    const { fileList, file } = info;
    const { record } = this.state;
    //后端成功返回数据
    if (file.status === 'done') {
      const { msg, code, data } = file.response;
      if (code === 0) {
        for (let i = 0; i < fileList.length; i++) {
          if (file.uid === fileList[i].uid) {
            fileList[i].thumbUrl = data.fileUrl;
            fileList[i].fileSuffix = data.fileSuffix;
          }
        }
        record.picList = fileList;
        //只取第一张图片
        if (fileList.length > 0) {
          record.imgUrl = fileList[0].thumbUrl;
        }
        this.setState({ record: record });
        message.success('上传文件成功！！');
      } else {
        //去掉没上传成功的
        for (let i = 0; i < fileList.length; i++) {
          if (file.uid === fileList[i].uid) {
            fileList.splice(i, 1);
          }
        }
        record.picList = fileList;
        this.setState({ record: record });
        message.error('上传文件失败！！' + msg);
      }
    }
    //正在上传
    if (file.status === 'uploading') {
      record.picList = fileList;
      this.setState({ record: record });
    }
  };
  //删除图片
  handleRemove = info => {
    const { record } = this.state;
    const picList = record.picList;
    for (let i = 0; i < picList.length; i++) {
      if (info.uid === picList[i].uid) {
        picList.splice(i, 1);
      }
    }
    record.picList = picList;
    this.setState({ record: record });
    message.success('删除文件成功！！');
  };
  //上传之前校验文件类型
  handleBeforeUpload = file => {
    const isJPG =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/gif' ||
      file.type === 'video/mp4';
    if (!isJPG) {
      message.error('只能上传图片类型！！例如：jpg、png、gif');
    }
    return isJPG;
  };

  //选定产品信息
  selectProduceInfo = () => {
    debugger;
    const { selectProductList, record } = this.state;
    if (selectProductList.length == 0) {
      message.error('必须选择一个产品！！');
      return;
    }
    if (selectProductList.length > 1) {
      message.error('只能选择一个产品，请确认已选择的产品！！');
      return;
    }
    record.productId = selectProductList[0].id;
    record.productTitle = selectProductList[0].productName;
    this.setState({ selectProductListVisible: false, record: record });
  };
  //关闭
  selectProductListVisibleCancel = () => this.setState({ selectProductListVisible: false });

  render() {
    const { form } = this.props;
    const { previewVisible, previewImage, record } = this.state;
    return (
      <Form onSubmit={this.okHandler}>
        {form.getFieldDecorator('id', {
          initialValue: record.id ? record.id : null,
        })(<Input type="hidden" />)}
        {form.getFieldDecorator('imgUrl', {
          initialValue: record.imgUrl ? record.imgUrl : null,
        })(<Input type="hidden" />)}
        {form.getFieldDecorator('productId', {
          initialValue: record.productId ? record.productId : null,
        })(<Input type="hidden" placeholder="请输入产品id" />)}
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="首页轮播图">
          {form.getFieldDecorator('picList', {
            rules: [{ validator: this.checkImageList, message: '请上传产品展示图', type: 'array' }],
            initialValue: record.picList.length !== 0 ? record.picList : [],
          })(
            <div className="clearfix">
              <Upload
                action="/api/sys/file/uploadFile"
                headers={{
                  authorization: localStorage.getItem('token'),
                }}
                listType="picture-card"
                fileList={record.picList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
                onRemove={this.handleRemove}
                beforeUpload={this.handleBeforeUpload}
                multiple={true}
              >
                {record.picList.length >= 5 ? null : (
                  <div>
                    <Icon type="plus" />
                    <div className="ant-upload-text">上传</div>
                  </div>
                )}
              </Upload>
              <Modal
                visible={previewVisible}
                footer={null}
                onCancel={this.handleCancel}
                width={1300}
              >
                <img alt="example" style={{ width: '100%', height: '100%' }} src={previewImage} />
              </Modal>
            </div>
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="产品标题">
          <Modal
            title="选择产品"
            visible={this.state.selectProductListVisible}
            onOk={this.selectProduceInfo}
            onCancel={this.selectProductListVisibleCancel}
            width={1200}
          >
            <SelectProductInfo parent={this}></SelectProductInfo>
          </Modal>
          <Button
            type="primary"
            onClick={() => {
              this.setState({ selectProductListVisible: true });
            }}
          >
            选择产品
          </Button>
          {form.getFieldDecorator('productTitle', {
            rules: [{ required: true, message: '请输入产品标题' }],
            initialValue: record.productTitle ? record.productTitle : null,
          })(<Input placeholder="请输入产品标题" disabled={true} />)}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="排序号">
          {form.getFieldDecorator('sortNum', {
            rules: [{ required: true, message: '请输入排序号' }],
            initialValue: record.sortNum ? record.sortNum : null,
          })(<Input placeholder="请输入排序号" />)}
        </FormItem>
      </Form>
    );
  }
}
